/*
 * Copyright (C) 2013 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package ac.neec.mio.ui.activity;

import ac.neec.core.ble.util.BleUtil;
import ac.neec.data.HeartRate;
import ac.neec.listener.EventsCallBackListener;
import ac.neec.listener.HeartRateEventListener;
import ac.neec.mio.R;
import ac.neec.mio.ui.fragment.ConnectBLEFlagment;
import ac.neec.mio.ui.fragment.RestingMeasurementFragment;
import android.app.Activity;
import android.app.FragmentTransaction;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

public class RestingMeasurementActivity extends BLEActivity implements EventsCallBackListener<Object> {
        public static final String BACK_STACK_BLE_CONNECT_ADD = "BLE Connect Setting ADD";
        public static final String BACK_STACK_RESR_MEASUREMENT_FRAGMENT_ADD = "RestingMeasurementFragment ADD";
        public static final int CALLBACK_ID_CONNECT_BLE_FRAGMENT = 10;
        public static final int CALLBACK_ID_MEASUREMENT_START = 11;
        public static final int CALLBACK_ID_MEASUREMENT_STOP = 12;
        private static final int REQUEST_ENABLE_BLUETOOTH = 0;
        private HeartRateEventListener<Object> mEventListener;
        private EventsCallBackListener<Integer> mCallbackListener;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_measurement_test);
                try {
                        mCallbackListener = (EventsCallBackListener<Integer>) getIntent().getSerializableExtra("Callback");
                } catch (ClassCastException e) {
                        e.printStackTrace();
                }

                startupBluetooth();
                setupOnCreate();
        }

        private void startupBluetooth() {
                //      TODO BLE Support check
                if (!BleUtil.isBLESupported(this)) {
                        Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
                        finish();
                }
                BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
                if (btAdapter == null) {
                        //         alertBluetoothUnsupported();
                } else {
                        if (!btAdapter.isEnabled()) {
                                Intent intent = new Intent(
                                                BluetoothAdapter.ACTION_REQUEST_ENABLE);
                                startActivityForResult(intent, REQUEST_ENABLE_BLUETOOTH);
                        }
                        else {
                                startupConnectBLEFragment();
                        }
                }
        }

        private void startupConnectBLEFragment() {
                ConnectBLEFlagment fragment = new ConnectBLEFlagment();
                FragmentTransaction transaction = getFragmentManager().beginTransaction();
                transaction.add(R.id.act_measurement_test_container, fragment);
                transaction.addToBackStack(BACK_STACK_BLE_CONNECT_ADD);
                transaction.commit();

        }

        private void startupRestingMeasurement(BluetoothDevice device) {
                //TODO Connect BLE Device
                setupBLEConnect(device, this);
                RestingMeasurementFragment fragment = new RestingMeasurementFragment();
                try {
                        mEventListener = (HeartRateEventListener) fragment;
                } catch (ClassCastException e) {
                        throw new ClassCastException(fragment.toString() + " must implement OnArticleSelectedListener");
                }
                setupOnCreate();
                FragmentTransaction transaction = getFragmentManager().beginTransaction();
                transaction.replace(R.id.act_measurement_test_container, fragment);
                transaction.addToBackStack(BACK_STACK_RESR_MEASUREMENT_FRAGMENT_ADD);
                transaction.commit();

        }

        @Override
        protected void onResume() {
                super.onResume();
                setupOnResume();
        }

        @Override
        protected void onPause() {
                super.onPause();
                setupOnPause();
        }

        @Override
        protected void onDestroy() {
                super.onDestroy();
                setupOnDestroy();
        }

        @Override
        protected void onActivityResult(int requestCode, int ResultCode, Intent date) {
                if (requestCode == REQUEST_ENABLE_BLUETOOTH) {
                        if (ResultCode == Activity.RESULT_OK) {
                                startupConnectBLEFragment();
                        } else {
                                //alertBluetoothUnAccept();
                                //TODO
                                Toast.makeText(getApplicationContext(), "Bluetooth unactive", Toast.LENGTH_SHORT).show();
                        }
                }
        }

        @Override
        protected void updateConnectionState(int resourceId) {

        }

        @Override
        protected void clearUI() {

        }

        @Override
        protected void displayData(String data) {
                if (mEventListener == null) {
                        Log.e("EventListener", "null pointer");
                }
                else {
                        mEventListener.notifyHeartRateEvent(data);
                }
        }

        @Override
        public void onCallBack(int id, Object value) {
                switch (id) {
                case CALLBACK_ID_CONNECT_BLE_FRAGMENT:
                        BluetoothDevice device = (BluetoothDevice) value;
                        startupRestingMeasurement(device);
                        break;
                case CALLBACK_ID_MEASUREMENT_START:
                        setupReadCharacteristic();
                        setupOnResume();
                        break;
                case CALLBACK_ID_MEASUREMENT_STOP:
                        HeartRate item = (HeartRate) value;
                        Log.e("", "item = "+value);
//                        RestingMeasurementManager.mRestingHeartRate = item.getRestingHeartRate();
                        finish();
                        break;
                }
        }

        @Override
        protected void notifyServiceConnecttion(boolean flag) {
                if (flag == false)
                        return;
                RestingMeasurementFragment fragment = new RestingMeasurementFragment();
                try {
                        mEventListener = (HeartRateEventListener) fragment;
                } catch (ClassCastException e) {
                        throw new ClassCastException(fragment.toString() + " must implement OnArticleSelectedListener");
                }
                setupOnCreate();
                FragmentTransaction transaction = getFragmentManager().beginTransaction();
                transaction.replace(R.id.act_measurement_test_container, fragment);
                transaction.addToBackStack(BACK_STACK_RESR_MEASUREMENT_FRAGMENT_ADD);
                transaction.commit();
        }

}
